package com.ehotting.eaf.netty.code;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.List;


public class ByteToCommandDecoder extends ByteToMessageDecoder {
	
	private final Logger logger = LoggerFactory.getLogger(ByteToCommandDecoder.class);

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) {
		int readableBytesLen =  buf.readableBytes();
		if(readableBytesLen<=6){
			return;
		}
	 	buf.markReaderIndex();
	 		
 		buf.readBytes(new byte[2]);
 		int msgLen = buf.readInt();
 		
 		if (msgLen < 0) { 
 			// 我们读到的消息体长度为0，这是不应该出现的情况，这里出现这情况，关闭连接。
 			logger.error("msgLen[{}] < 0,close ctx.",msgLen);
            ctx.close();
        }
 		
 		if((msgLen+6)>readableBytesLen){
 			//logger.error("readableBytesLen[{}]<msgLen[{}]+6 is error,return.",readableBytesLen,msgLen);
 			buf.resetReaderIndex();
 			return;
 		}
 		
 		byte[] msg = new byte[msgLen];
 		buf.readBytes(msg);
 		out.add(new String(msg, StandardCharsets.UTF_8));
	}
}
